package com.hanj.myserver.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zjiecode.wxpusher.client.WxPusher;
import com.zjiecode.wxpusher.client.bean.Result;
import com.zjiecode.wxpusher.client.bean.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 发送消息
 *
 * @author hanj.cn @outlook.com
 */
public class SendMsg {

    /**
     * 发送消息到bark客户端
     *
     * @param groupName 组名
     * @param title     标题
     * @param content   内容
     */
    public static void byBark(String groupName, String title, String content) {

        String url = Initialization.getIpBark() + "/" + Initialization.getDeviceCode() + "/" + title + "/" + content + "?group=" + groupName;
        HttpUtil.get(url);

    }

    /**
     * 向企业微信发送消息
     *
     * @param targetName 目标用户
     * @param msg        消息
     */
    public static void byWx(String targetName, String msg) {

        // 获取token
        String accessToken = MyUtil.getWxAccessToken();

        // 构造消息体
        HashMap<Object, Object> body = new HashMap<>(9);
        HashMap<String, String> content = new HashMap<>(1);

        content.put("content", msg);

        body.put("touser", targetName);
        body.put("msgtype", "text");
        body.put("agentid", 1000002);
        body.put("text", content);

        // 转为json
        String bodyStr = JSONUtil.toJsonStr(body);

        // 拼接url
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        // 发送post请求
        HttpUtil.post(url, bodyStr);
    }

    /**
     * 通过WxPusher发送全体消息
     */
    public static void byWxPusher(String summary, String content, ArrayList<String> uids, boolean isToAll) {

        Message message = new Message();
        message.setAppToken(Initialization.getAppToken());
        message.setSummary(summary);
        message.setContentType(Message.CONTENT_TYPE_TEXT);
        message.setContent(content);

        if (isToAll) {
            Result<Page<WxUser>> wxUsers = WxPusher.queryWxUser(Initialization.getAppToken(), 1, 50);

            List<WxUser> uIdList = wxUsers.getData().getRecords();

            for (WxUser wxUser : uIdList) {
                message.setUid(wxUser.getUid());
                Result<List<MessageResult>> result = WxPusher.send(message);
            }
        } else {
            for (String uid : uids) {
                message.setUid(uid);

                Result<List<MessageResult>> result = WxPusher.send(message);
            }
        }

    }

}
